package b_nio;

import java.nio.ByteBuffer;
import java.util.Arrays;

public class GetBufferDemo {

    public static void main(String[] args) {
        // 1.创建一个指定长度的缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byteBuffer.put("0123456789".getBytes());
        System.out.println("position:" + byteBuffer.position()); // 4
        System.out.println("limit:" + byteBuffer.limit()); //10
        System.out.println(byteBuffer.get());
        // 切换读模式
        System.out.println("切换读模式--------------");
        byteBuffer.flip();
        System.out.println("position:" + byteBuffer.position()); // 0
        System.out.println("limit:" + byteBuffer.limit()); // 4
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.println(byteBuffer.get());
        }
        // 读取完毕后，继续读取会报错，超过limit值
        //System.out.println(byteBuffer.get());
        //读取指定索引字节
        System.out.println("读取指定索引字节--------------");
        System.out.println(byteBuffer.get(1));
        System.out.println("读取多个字节--------------");
        // 重复读取
        byteBuffer.rewind();
        byte[] bytes = new byte[4];
        byteBuffer.get(bytes);
        System.out.println(new String(bytes)); // 0123
        // 将缓冲区转化字节数组返回
        byte[] array = byteBuffer.array();
        System.out.println(new String(array)); // 0123后面还有6个空格
        System.out.println("切换写模式--------------");
        byteBuffer.clear();
        byteBuffer.put("abc".getBytes());
        System.out.println(new String(byteBuffer.array())); //abc3
    }
}
